import { useState, useMemo } from 'react'
import { Layout, Menu } from 'antd'
import { useNavigate, useLocation } from 'react-router'
import {
    MenuFoldOutlined,
    MenuUnfoldOutlined,
} from '@ant-design/icons'
import { useRouteStore } from '@/store'
import './style.less'

const AntdSider = Layout.Sider

// 提取菜单项递归生成
function getMenuItemsFromRoutes(routes, navigate) {
    return routes
      .filter(route => !route.hidden && route.meta && route.meta.title)
      .map(route => {
        let children = route.children ? getMenuItemsFromRoutes(route.children, navigate) : []
        return {
          label: route.meta.title,
          key: route.path,
          icon: route.meta.icon,
          children: children.length > 0 ? children : null,
          onClick: () => navigate(route.path)
        }
      })
}

function Sider() {
    const location = useLocation()
    const navigate = useNavigate()
    const [collapsed, setCollapsed] = useState(false)
    const { routes } = useRouteStore()


    // 生成菜单项
    const items = useMemo(() => getMenuItemsFromRoutes(routes, navigate), [routes, navigate])
    // 切换左侧导航开合状态
    const onCollapse = () => {
        setCollapsed(!collapsed)
    }

    // 左侧导航展开时的宽度
    const fullWidth = 200
    // 左侧导航收起时的宽度
    const collapsedWidth = 49

    return (
        <AntdSider
            className="M-sider"
            trigger={null}
            collapsible
            collapsed={collapsed}
            collapsedWidth={collapsedWidth}
            width={fullWidth}
        >
            <div className="sider-main">
                <Menu
                    mode="inline"
                    selectedKeys={[location.pathname]}
                    items={items}
                    className="sider-menu"
                ></Menu>
                <div className="sider-footer" onClick={onCollapse} style={{ color: '#ffffff' }}>
                    {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
                </div>
            </div>
        </AntdSider>
    )
}

export default Sider
